import React, { useState, useRef, useEffect } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  TextInput, 
  TouchableOpacity, 
  ScrollView, 
  SafeAreaView,
  ActivityIndicator,
  Alert,
  Dimensions,
  StatusBar,
  Clipboard
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../../navigation/types';
import DocumentTypeLengthModal from './TypeLengthModal';
import LengthSelectionModal from './LengthModal';

const { width } = Dimensions.get('window');

// API相关常量
const API_URL = 'https://api.coze.cn/v3/chat';
const API_KEY = "Bearer pat_72lCfOZdDlQRo5YET5kK2w4ookRhbO4oqRGQCaq7BwxfxzP9TTgRQLca6pxzWjNE";
const BOT_ID = "7488896260741726258";
const USER_ID = "123123***";

const AITextGenerationScreen = () => {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const scrollViewRef = useRef<ScrollView>(null);
  
  // 输入相关状态
  const [inputText, setInputText] = useState('');
  const [textLength, setTextLength] = useState(0);
  const maxLength = 200;
  
  // 模态框状态
  const [typeModalVisible, setTypeModalVisible] = useState(false);
  const [lengthModalVisible, setLengthModalVisible] = useState(false);
  
  // 选项状态
  const [selectedType, setSelectedType] = useState('通用');
  const [selectedStyle, setSelectedStyle] = useState('通用');
  const [selectedLength, setSelectedLength] = useState('1000-2000');
  const [selectedEffect, setSelectedEffect] = useState('优质');
  
  // 生成状态
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedText, setGeneratedText] = useState('');
  const [isResultVisible, setIsResultVisible] = useState(false);
  
  // 处理类型/风格选择
  const handleTypeStyleSubmit = (data: { type: string, style: string }) => {
    setSelectedType(data.type);
    setSelectedStyle(data.style);
  };
  
  // 处理文档长度选择
  const handleLengthSubmit = (length: string) => {
    setSelectedLength(length);
  };
  
  // 处理开始生成
  const handleGenerate = async () => {
    if (!inputText.trim()) {
      Alert.alert('提示', '请输入题目或主题');
      return;
    }
    
    // 确保在本页面显示结果
    setIsGenerating(true);
    setIsResultVisible(true); // 显示结果区域
    setGeneratedText(''); // 清空之前的内容
    
    // 确保立即滚动到显示区域
    setTimeout(() => {
      scrollViewRef.current?.scrollToEnd({ animated: true });
    }, 100);
    
    try {
      // 准备请求数据
      const prompt = `请以"${selectedType}"类型和"${selectedStyle}"风格写一篇关于"${inputText}"的文章，字数在${selectedLength}字左右。`;
      const requestBody = {
        "bot_id": BOT_ID,
        "user_id": USER_ID,
        "stream": true,
        "auto_save_history": true,
        "additional_messages": [
          {
            "role": "user",
            "content": prompt,
            "content_type": "text"
          }
        ]
      };

      // 发送API请求
      const response = await fetch(API_URL, {
        method: 'POST',
        headers: {
          "Authorization": API_KEY,
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream'
        },
        body: JSON.stringify(requestBody)
      });

      if (!response.ok) {
        throw new Error(`HTTP 错误! 状态: ${response.status}`);
      }

      // 使用文本处理的方式
      const responseText = await response.text();
      processStreamResponse(responseText);
      
    } catch (error) {
      console.error('生成内容时出错:', error);
      Alert.alert('错误', `生成内容失败: ${error.message}`);
      setIsGenerating(false);
    }
  };

  // 处理流式响应
  const processStreamResponse = (responseText: string) => {
    const lines = responseText.split('\n');
    let fullContent = '';
    let index = 0;

    // 模拟打字机效果
    const processNextLine = () => {
      if (index < lines.length) {
        const line = lines[index].trim();
        
        if (line.startsWith('data:')) {
          const jsonData = line.substring(5).trim();
          
          if (jsonData && jsonData !== '[DONE]') {
            try {
              const data = JSON.parse(jsonData);
              
              // 专门查找content内容
              if (data.type === 'answer' && data.content && data.content_type === 'text') {
                // 流式追加内容
                fullContent += data.content;
                setGeneratedText(prevText => prevText + data.content);
              }
            } catch (e) {
              console.error('解析JSON失败:', e);
            }
          }
        }
        
        index++;
        setTimeout(processNextLine, 10); // 控制打字机效果的速度
      } else {
        // 所有行处理完毕
        setIsGenerating(false);
        
        // 自动滚动到底部
        if (scrollViewRef.current) {
          setTimeout(() => {
            scrollViewRef.current?.scrollToEnd({ animated: true });
          }, 100);
        }
      }
    };

    processNextLine();
  };

  // 返回到输入界面
  const handleBackToInput = () => {
    setIsResultVisible(false);
  };

  // 复制生成的内容
  const handleCopyContent = () => {
    if (generatedText) {
      Clipboard.setString(generatedText);
      Alert.alert('复制成功', '内容已复制到剪贴板');
    }
  };

  useEffect(() => {
    // 当结果可见时，确保滚动到底部
    if (isResultVisible && scrollViewRef.current) {
      const timer = setTimeout(() => {
        scrollViewRef.current?.scrollToEnd({ animated: true });
      }, 300); // 给更多时间让视图更新
      
      return () => clearTimeout(timer);
    }
  }, [isResultVisible, generatedText]);

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity 
          onPress={() => isResultVisible ? handleBackToInput() : navigation.goBack()} 
          style={styles.backButton}
        >
          <Text style={styles.backButtonText}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>全文生成</Text>
        <View style={styles.emptySpace}></View>
      </View>
      
      <ScrollView 
        ref={scrollViewRef}
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
      >
        {!isResultVisible ? (
          // 输入界面
          <>
            {/* 主题输入框 */}
            <View style={styles.inputSection}>
              <Text style={styles.inputLabel}>请输入题目或主题<Text style={styles.requiredStar}>*</Text></Text>
              <TextInput
                style={styles.input}
                placeholder="例如：人工智能技术的历史和应用场景"
                placeholderTextColor="#BBBBBB"
                multiline
                value={inputText}
                onChangeText={(text) => {
                  setInputText(text);
                  setTextLength(text.length);
                }}
                maxLength={maxLength}
              />
              <Text style={styles.counter}>{textLength}/{maxLength}</Text>
            </View>
            
            {/* 全文类型/风格 */}
            <TouchableOpacity 
              style={styles.selectSection}
              onPress={() => setTypeModalVisible(true)}
            >
              <View style={styles.selectSectionRow}>
                <Text style={styles.sectionLabel}>全文类型/风格</Text>
                <View style={styles.selectedValueContainer}>
                  <Text style={styles.selectedValue}>{selectedType}/{selectedStyle}</Text>
                  <Text style={styles.arrowRight}>{'>'}</Text>
                </View>
              </View>
            </TouchableOpacity>
            
            {/* 全文长度 */}
            <TouchableOpacity 
              style={styles.selectSection}
              onPress={() => setLengthModalVisible(true)}
            >
              <View style={styles.selectSectionRow}>
                <Text style={styles.sectionLabel}>全文长度</Text>
                <View style={styles.selectedValueContainer}>
                  <Text style={styles.selectedValue}>{selectedLength}</Text>
                  <Text style={styles.arrowRight}>{'>'}</Text>
                </View>
              </View>
            </TouchableOpacity>
            
            {/* 效果选择 */}
            <View style={styles.effectSection}>
              <Text style={styles.sectionLabel}>效果</Text>
              <View style={styles.effectOptions}>
                <TouchableOpacity 
                  style={[styles.effectOption, selectedEffect === '优质' && styles.effectOptionSelected]}
                  onPress={() => setSelectedEffect('优质')}
                >
                  <Text style={[styles.effectOptionText, selectedEffect === '优质' && styles.effectOptionTextSelected]}>优质</Text>
                </TouchableOpacity>
                
                <TouchableOpacity 
                  style={[styles.effectOption, selectedEffect === '超优质' && styles.effectOptionSelected]}
                  onPress={() => setSelectedEffect('超优质')}
                >
                  <Text style={[styles.effectOptionText, selectedEffect === '超优质' && styles.effectOptionTextSelected]}>超优质</Text>
                </TouchableOpacity>
                
                <TouchableOpacity 
                  style={[styles.effectOption, selectedEffect === '引用网络数据' && styles.effectOptionSelected]}
                  onPress={() => setSelectedEffect('引用网络数据')}
                >
                  <Text style={[styles.effectOptionText, selectedEffect === '引用网络数据' && styles.effectOptionTextSelected]}>引用网络数据</Text>
                </TouchableOpacity>
              </View>
              <Text style={styles.effectNote}>注：使用优质模型，内容效果和长度优秀。</Text>
            </View>
            
            {/* 生成按钮 */}
            <TouchableOpacity 
              style={styles.generateButton} 
              onPress={handleGenerate}
              disabled={isGenerating}
            >
              {isGenerating ? (
                <ActivityIndicator color="#fff" size="small" />
              ) : (
                <Text style={styles.generateButtonText}>开始生成</Text>
              )}
            </TouchableOpacity>
            
            {/* 免责声明 */}
            <Text style={styles.disclaimer}>内容由AI生成，不可视为真实数据，不可作非法用途。</Text>
          </>
        ) : (
          // 结果界面
          <View style={styles.resultContainer}>
            {/* 结果标题 */}
            <View style={styles.resultTitleContainer}>
              <Text style={styles.resultTitle}>{inputText}</Text>
              <View style={styles.resultMeta}>
                <Text style={styles.resultMetaText}>类型/风格: {selectedType}/{selectedStyle}</Text>
                <Text style={styles.resultMetaText}>长度范围: {selectedLength}</Text>
                <Text style={styles.resultMetaText}>效果: {selectedEffect}</Text>
              </View>
            </View>
            
            {/* 生成内容区域 */}
            <View style={styles.contentContainer}>
              {isGenerating && !generatedText && (
                <View style={styles.loadingContainer}>
                  <ActivityIndicator size="large" color="#4A90E2" />
                  <Text style={styles.loadingText}>正在生成内容，请稍候...</Text>
                </View>
              )}
              
              {generatedText ? (
                <>
                  <Text style={styles.contentText}>{generatedText}</Text>
                  
                  {/* 正在生成的指示器 */}
                  {isGenerating && (
                    <View style={styles.typingIndicator}>
                      <Text style={styles.typingText}>AI正在思考</Text>
                      <ActivityIndicator size="small" color="#4A90E2" style={styles.typingDots} />
                    </View>
                  )}
                  
                  {/* 操作按钮 */}
                  {!isGenerating && (
                    <View style={styles.actionButtons}>
                      <TouchableOpacity style={styles.actionButton} onPress={handleCopyContent}>
                        <Text style={styles.actionButtonText}>复制全文</Text>
                      </TouchableOpacity>
                    </View>
                  )}
                </>
              ) : null}
            </View>
          </View>
        )}
      </ScrollView>
      
      {/* 类型/风格选择模态框 */}
      <DocumentTypeLengthModal
        visible={typeModalVisible}
        onClose={() => setTypeModalVisible(false)}
        onSubmit={handleTypeStyleSubmit}
      />
      
      {/* 长度选择模态框 */}
      <LengthSelectionModal
        visible={lengthModalVisible}
        onClose={() => setLengthModalVisible(false)}
        onSubmit={handleLengthSubmit}
        initialValue={selectedLength}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    marginTop: StatusBar.currentHeight || 0,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    height: 50,
    backgroundColor: '#FFFFFF',
    borderBottomWidth: 1,
    borderBottomColor: '#EEEEEE',
  },
  backButton: {
    padding: 8,
  },
  backButtonText: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  emptySpace: {
    width: 40,
  },
  scrollView: {
    flex: 1,
  },
  inputSection: {
    backgroundColor: '#FFFFFF',
    marginTop: 15,
    borderRadius: 8,
    padding: 15,
    marginHorizontal: 15,
  },
  inputLabel: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333333',
  },
  requiredStar: {
    color: 'red',
  },
  input: {
    backgroundColor: '#F5F5F5',
    borderRadius: 8,
    paddingHorizontal: 15,
    paddingVertical: 15,
    paddingTop: 15,
    minHeight: 100,
    fontSize: 16,
    textAlignVertical: 'top',
  },
  counter: {
    textAlign: 'right',
    marginTop: 8,
    color: '#999999',
    fontSize: 14,
  },
  selectSection: {
    backgroundColor: '#FFFFFF',
    marginTop: 15,
    marginHorizontal: 15,
    borderRadius: 8,
  },
  selectSectionRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
  },
  sectionLabel: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333333',
  },
  selectedValueContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  selectedValue: {
    fontSize: 16,
    color: '#666666',
    marginRight: 5,
  },
  arrowRight: {
    fontSize: 16,
    color: '#999999',
  },
  effectSection: {
    backgroundColor: '#FFFFFF',
    marginTop: 15,
    marginHorizontal: 15,
    borderRadius: 8,
    padding: 15,
  },
  effectOptions: {
    flexDirection: 'row',
    marginTop: 15,
    marginBottom: 10,
  },
  effectOption: {
    backgroundColor: '#F5F5F5',
    paddingVertical: 8,
    paddingHorizontal: 16,
    borderRadius: 20,
    marginRight: 10,
  },
  effectOptionSelected: {
    backgroundColor: '#4A90E2',
  },
  effectOptionText: {
    color: '#666666',
    fontSize: 14,
  },
  effectOptionTextSelected: {
    color: '#FFFFFF',
  },
  effectNote: {
    fontSize: 14,
    color: '#999999',
    marginTop: 5,
  },
  generateButton: {
    backgroundColor: '#4A90E2',
    marginTop: 30,
    marginHorizontal: 15,
    borderRadius: 25,
    paddingVertical: 15,
    alignItems: 'center',
  },
  generateButtonText: {
    color: '#FFFFFF',
    fontSize: 18,
    fontWeight: 'bold',
  },
  disclaimer: {
    textAlign: 'center',
    color: '#999999',
    fontSize: 12,
    marginVertical: 20,
    marginHorizontal: 15,
  },
  // 结果页面样式
  resultContainer: {
    flex: 1,
    paddingHorizontal: 15,
    paddingTop: 15,
  },
  resultTitleContainer: {
    backgroundColor: '#FFFFFF',
    borderRadius: 8,
    padding: 15,
    marginBottom: 15,
  },
  resultTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333333',
    marginBottom: 10,
  },
  resultMeta: {
    borderTopWidth: 1,
    borderTopColor: '#EEEEEE',
    paddingTop: 10,
  },
  resultMetaText: {
    fontSize: 14,
    color: '#666666',
    marginBottom: 5,
  },
  contentContainer: {
    backgroundColor: '#FFFFFF',
    borderRadius: 8,
    padding: 15,
    marginBottom: 20,
    minHeight: 300,
  },
  contentText: {
    fontSize: 16,
    lineHeight: 24,
    color: '#333333',
  },
  loadingContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 50,
  },
  loadingText: {
    marginTop: 15,
    fontSize: 16,
    color: '#666666',
  },
  typingIndicator: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 20,
    padding: 10,
    backgroundColor: '#F5F5F5',
    borderRadius: 8,
  },
  typingText: {
    fontSize: 14,
    color: '#666666',
  },
  typingDots: {
    marginLeft: 8,
  },
  actionButtons: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 20,
  },
  actionButton: {
    backgroundColor: '#4A90E2',
    padding: 12,
    borderRadius: 8,
    minWidth: 120,
    alignItems: 'center',
  },
  actionButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '500',
  },
});

export default AITextGenerationScreen; 